<template>
	<view>
				<uni-section title="基本用法" type="line">
					<view class="example">
						<!-- 基础用法，不包含校验规则 -->
						<uni-forms ref="baseForm" :model="baseFormData" labelWidth="80px">
							<uni-forms-item label="配送">
							<uni-datetime-picker type="date" return-type="timestamp" v-model="billDate"  /></uni-forms-item>

							<uni-forms-item label="客户" required>
								<uni-data-select
										placeholder="请选择客户"
										v-model="customerId"
										:localdata="customerData"

								    ></uni-data-select>
							</uni-forms-item>


							<uni-forms-item>


								 <button @tap="openGoodsCategory" style="width: 120px;" class="bg-main cr-white round"  type="default" hover-class="none">选择物料</button>
								 <goods-category @updateShopCarMethod="updateShopCar" ref="goodsCategoryForm"></goods-category>
							</uni-forms-item>

							<!-- 订单基础数据 -->
							<view v-if="detail_list.length > 0" style="border: 1px solid silver;" class="panel-item padding-main border-radius-main bg-white spacing-mb">
							<uni-swipe-action>
							    <view v-for="(item, index) in detail_list" :key="index" class="oh border-radius-main bg-white spacing-mb">
							        <uni-swipe-action-item>
							            <view class="cart-goods-item padding-main pr cart-exhibition-mode-data" style="border-bottom: 1px silver dashed;">
							                <view class="items oh padding-left-sm">
							                    <view class="cart-goods-base">
							                        <view class="cart-goods-title margin-bottom-sm cr-grey" style="height: 26px;">
														<view class="fl">
															{{item.title}}
															<text v-if="item.spec != null">({{item.spec}})</text>
														</view>
														<view class="fr">
															<input type="text" v-model="inputs[index]" :ref="`child${item.id}`"  style="border: 1px solid #e5e5e5;width: 100%;height: 26px;font-size: 18px;" placeholder="备注" />
														</view>

													</view>
							                        <view class="goods-bottom margin-top-sm " >
														<view class="fl">
															<text ><text class="sales-price" style="padding-right: 4px;">￥{{item.price}}/{{item.unitName}}</text> </text>
															<text> 合计:<text class="sales-price">￥{{item.price*item.stock}}</text></text>
														</view>

							                            <view class="fr cart-number-content" >
							                                <view class="number-submit tc cr-gray fl va-m padding-right" @tap="goods_buy_number_event"  :data-index="index" data-type="0">-</view>
							                                <input class="tc cr-gray fl va-m radius-0"  @click="openKeyBoard" style="width: 40px;background-color: beige;" disabled="true" @blur="goods_buy_number_blur"  type="number" :value="item.stock" :data-index="index">
							                                <view class="number-submit tc cr-gray fl va-m padding-left" @tap="goods_buy_number_event"  :data-index="index" data-type="1">+</view>
							                            </view>

							                        </view>
							                    </view>
							                </view>
							            </view>
							        </uni-swipe-action-item>
							    </view>
							</uni-swipe-action>
							</view>



							<uni-forms-item label="备注">
								<uni-easyinput type="textarea" v-model="salRemark" placeholder="请输入备注" />
							</uni-forms-item>


						</uni-forms>


						<view :class="'cart-buy-nav oh wh-auto br-t bg-white '+(source_type != 'cart' ? 'bottom-line-exclude' : '')">
						    <view class="cart-nav-base fl single-text padding-left">
						    </view>
						    <view class="fr cart-nav-submit padding-top padding-bottom padding-horizontal-main">
						        <button @tap="buy_submit_event" class="bg-green cr-white text-size-lg round" type="default" hover-class="none">创建订单</button>
						    </view>
						</view>
					</view>
				</uni-section>

			<view style="position: fixed;bottom: 15px;width: 100%;margin: 2px">
			  <button class="bg-green cr-white round text-size-lg" style="width: 98%;" type="default"   @longpress="longpressBtn" @touchend="touchendBtn"  hover-class="none"> <text>{{longPress == '1' ? '按住说话' : '说话中...'}}</text></button>
			</view>
			<view style="height: 50px;"></view>
				<!-- 数字键盘 -->
				<block v-if="keyboard_status">
					                    <view class="cart-mask wh-auto ht-auto pf" @tap="keyboard_event"></view>
					                    <view class="cart-content bg-white border-radius-main pa oh">
					                        <block>
					                            <view class="oh br-b padding-vertical-main padding-horizontal-main">
													<view sclass="input-content">&nbsp;{{ inputValue.join("") }}</view>
													<view class="confirm-btn" @click="confirm">确定</view>
					                            </view>
					                            <scroll-view :scroll-y="true" class="cart-list goods-list">
					                                <view class="item padding-main oh spacing-mb">
					                                    <view>
															  <view class="modal"  :animation="animationData1" @touchmove.stop.prevent>
																<view class=" content-wrap" :animation="animationData2">
																  <view class="key-box">
																	<view

																	  v-for="(item, index) in keyboardList"
																	  :key="index"
																	  @click="setValue(item)"
																	  >{{ item }}</view
																	>
																  </view>
																</view>

															  </view>
														</view>
					                                </view>
					                            </scroll-view>
					                        </block>
					                    </view>
				</block>


				<block v-if="sound_status">
					    <view class="cart-mask wh-auto ht-auto pf"></view>
					            <view style="width: 140px;height: 40px;bottom: 250px;left: 30%;" class="cart-content bg-green border-radius-main pa oh">
					                        <block>
					                            <view style="padding: 10px 30px;">
													请说话·····

					                            </view>
                                    <view style="padding: 10px 30px;">
                                      你可以这样说:白菜5斤,排骨5斤

                                    </view>
					             </block>
					     </view>
				</block>


	</view>
</template>

<script>
	const app = getApp();
	let init // 录制时长计时器
	let timer; // 播放 录制倒计时
	const recorder = wx.getRecorderManager();
	import base64 from '../../common/js/lib/base64.js';
	import goodsCategory from "../../components/goods-category/goods-category"
	export default {
		data() {
			return {
				longPress: '1', // 1显示 按住说话 2显示 说话中
				inputs: [],
				salRemark:"",
				customerId:"",
				billDate:"",
				baseFormData:{},
				customerData:[],
				user: null,
				detail_list: [],
				inputValue: [],
				ywid:"",
				keyboard_status:false,
				sound_status:false,
				buy_submit_disabled_status: false,
			}
		},
		watch: {
		    // 当message变化时，这个函数就会被调用
		    customerId(newValue, oldValue) {
		      console.log(`消息从 "${oldValue}" 变为 "${newValue}"`);
			  if(newValue !== ""){
				  this.loadShopCar(true);
			  }

		      // 这里可以执行更多的逻辑
		    }
		},
		onLoad(params) {
			this.getCurrentTime();
			this.user = app.globalData.get_user_info(this, "init");
			this.initCustomer();


			if ((params.data || null) != null) {
			    this.setData({
			        params: JSON.parse(base64.decode(decodeURIComponent(params.data))),
			        plugins_points_status: app.globalData.get_config('plugins_base.points.data.is_default_use_points', null) == 1
			    });

			    // 删除地址缓存
			    uni.removeStorageSync(app.globalData.data.cache_buy_user_address_select_key);
			}
		},
		components: {
			goodsCategory
		},
		computed: {
			keyboardList() {
			  return this.decimals
				? ["1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "0", "删除"]
				: ["1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "0", "删除"];
			},
		},
		methods: {
			soundRecognize() {
			  console.log("ddddddddddddddddddddddfffff")
			  //语音识别
			  var user = app.globalData.get_user_info(this, "init");
			  if(user != null){
			    this.user =user;
			  }
			  const that =this;
			  // console.log("---------",this.audio_path)
			  // console.log("---111----",this.audio_data)

			  uni.request({
			    url: app.globalData.get_request_url("soundRecoAIApp"),
			    method: 'POST',
			    data: {base64data:this.audio_data,
			      "tenantId" : this.user.role.id,
				  "customerId" : this.customerId,
			      "createBy" : this.user.username,

			    },
			    header:{
			      'Tenant-Id':this.user.role.tenantId,
			      'X-Access-Token':this.user.token,
			    },
			    dataType: 'json',
			    success: res => {
			      uni.hideLoading();
			      console.log("res11111111111111",res);


			      if (res.data.code == 200) {
			        let data = res.data.data;
			        let orderMsg = res.data.orderMsg;
			        let flag = res.data.flag;
			        this.flag = flag;
			        if (res.data.isAdd == 1) {
			          //需要更新購物車數據
			          //  console.log("11111111111111111",data_list)
			          let data_list = data.data || [];
			          // this.setData({
			          //   data_list: data_list,
			          //   data_list_loding_status: data_list.length == 0 ? 0 : 3,
			          //   data_bottom_line_status: true,
			          //   data_list_loding_msg: '购物车空空如也'
			          // });
					  //需要更新購物車數據
					  that.loadShopCar(false);

			        }

			          if(orderMsg.trim()!=''){
			          uni.showModal({
			            title: '系统未找到对应的物料，语音下单内容为：',
			            content: orderMsg,
			            editable: true,
			            success: function (res) {
			              if (res.confirm) {
			                console.log('用户点击确定', res.content);
			                uni.request({
			                  url: app.globalData.get_request_url("textAi"),
			                  method: 'POST',
			                  data: {
			                    base64data: res.content,
			                    "customerId": that.user.role.id,
			                    "createBy": that.user.username,

			                  },
			                  header: {
			                    'Tenant-Id': that.user.role.tenantId,
			                    'X-Access-Token': that.user.token,
			                  },
			                  dataType: 'json',
			                  success: res => {
			                    uni.hideLoading();
			                    console.log("res1111111111111100000000000000000000000000", res);


			                    if (res.data.code == 200) {
			                      let data = res.data.data;
			                      let orderMsg = res.data.orderMsg;
			                      let flag = res.data.flag;
			                      this.flag = flag;
			                      if (res.data.isAdd == 1) {
			                        //需要更新購物車數據
									that.loadShopCar(false);
			                        // let data_list = data.data || [];
			                        // console.log("1111111111111111100000000000000000000000", data_list)
			                        // that.setData({
			                        //   data_list: data_list,
			                        //   data_list_loding_status: data_list.length == 0 ? 0 : 3,
			                        //   data_bottom_line_status: true,
			                        //   data_list_loding_msg: '购物车空空如也'
			                        // });



			                      } else {
			                        uni.showToast({
			                          title: '未找到对应物料，请重新下单',
			                          duration: 4000
			                        });


			                      }
			                    }
			                  },
			                  fail: () => {
			                    uni.hideLoading();
			                    app.globalData.showToast('服务器请求出错');
			                  }
			                });

			              } else if (res.cancel) {
			                console.log('用户点击取消');
			              }
			            }
			          });

			        }

			      }
			    },
			    fail: () => {
			      uni.hideLoading();
			      app.globalData.showToast('服务器请求出错');
			    }
			  });

			},
			start() { //语音触摸
			if(this.customerId === ""){
				app.globalData.showToast('请选择客户!');
				return;
			}
			  this.yyin = false;
			  const options = {
			    sampleRate: 16000,
			    numberOfChannels: 1,
			    format: "PCM",
			    lang: this.lang
			  };
			  recorder.start(options);
			  recorder.onStart(() => {
			    // console.log("Recording!~~~");
			  });
			  recorder.onError(err => {
			    console.log(err);
			  });
			},
			stop() { //语音结束触摸
			this.sound_status =false;
			   this.yyin = true;
			  recorder.stop();
			  recorder.onStop(res => {
			    //
			    this.audio_path = res.tempFilePath;

			    const fs = wx.getFileSystemManager();
			    fs.readFile({
			      filePath: this.audio_path,
			      encoding: 'base64',
			      success: (res) => {
			        this.audio_data = res.data;
			        //this.audio_data = this.arrayBufferToBase64(res.data);
			        this.soundRecognize();
			      }
			    });
			  });
			},
			// 倒计时
			countdown(val){
			  let _then = this;
			  _then.count = Number(val);
			  timer = setInterval(function() {
			    if(_then.count > 0){
			      _then.count--
			    } else {
			      _then.longPress = '1';
			      clearInterval(timer);
			    }
			  }, 1000);
			},
			// 长按松开录音事件
			touchendBtn(){
			  this.longPress = '1';
			  this.stop();
			},
			longpressBtn(){
			  //震动
			  wx.vibrateLong();

			  this.sound_status =true;

			  this.longPress = '2';
			  this.countdown(60); // 倒计时
			  this.isScanning =true;
			  this.start();
			},
			// 提交订单
			buy_submit_event(e) {
				if(this.customerId === ""){
					app.globalData.showToast('请选择客户!');
					return;
				}
				//console.log("-----",this.detail_list);
			    // 表单数据
				// 获取购物车数据
				var ids = [];
				if((this.detail_list || null) != null) {
				    var temp_data = this.detail_list || [];
				    for (var i in temp_data) {
				        ids.push(temp_data[i]['id']);
				    }
				}
			    var data = {remarks:this.inputs,ids:ids.join(","),customerId:this.customerId,userIdentity:this.user.userIdentity,roleId:this.user.role.id,billDate:this.billDate,salRemark:this.salRemark};

			    if (true) {
					let remarksEx =[];
					for(var i = 0; i < data['ids'].split(',').length; i++){
						if(i >= data['remarks'].length){
							remarksEx[i] = '';
						}else{
							if(typeof data['remarks'][i] === 'undefined'){
								remarksEx[i] = '';
							}else{
								remarksEx[i] = data['remarks'][i];
							}
						}
					}
					data['remarks'] =remarksEx;
					console.log("data",data)

					uni.showLoading({
					    title: '提交中...'
					});
			        uni.request({
			            url: app.globalData.get_request_url("createBuyOrder"),
			            method: 'POST',
			            data: data,
						header:{
							'Tenant-Id':this.user.role.tenantId,
							'X-Access-Token':this.user.token,
						},
			            dataType: 'json',
			            success: res => {
			                uni.hideLoading();
							console.log("res",res)
			                if (res.data.code == 0) {
			                    app.globalData.showToast('创建订单成功。');
								uni.redirectTo({
								    url: '/pages/user-order/user-order'
								});
			                } else {
			                    app.globalData.showToast(res.data.msg);
			                    this.setData({
			                        buy_submit_disabled_status: false
			                    });
			                }
			            },
			            fail: () => {
			                uni.hideLoading();
			                this.setData({
			                    buy_submit_disabled_status: false
			                });
			                app.globalData.showToast('服务器请求出错');
			            }
			        });
			    }
			},

			confirm() {
				//console.log("ywid===",this.ywid);
			  let buy_number = Number(this.inputValue.join(""));
			  var index =this.ywid;
			  this.goods_buy_number_func(index, buy_number);
			  this.keyboard_status =false;
			},
			setValue(data) {
			  this.activeKey = data;
			  let timer = setTimeout(() => {
			    this.activeKey = "-";
			    clearTimeout(timer);
			  }, 100);
			  if (
			    !data ||
			    (data !== "删除" &&
			      this.inputValue.includes(".") &&
			      this.inputValue.join("").split(".")[1].length === this.pointLength)
			  )
			    return false;
			  if (
			    this.inputValue.length === 1 &&
			    this.inputValue[0] === "0" &&
			    !["删除", "."].includes(data)
			  ) {
			    return (this.inputValue = [data]);
			  }

			  if (data !== "删除") {
			    if (this.inputValue.includes(".")) {
			      if (
			        this.inputValue.join("").split(".")[0].length === this.maxLength
			      ) {
			        return false;
			      }
			    } else if (this.inputValue.length === this.maxLength) {
			      return false;
			    }
			  }

			  if (data === "删除") {
			    return this.inputValue.length && this.inputValue.pop();
			  }
			  if (data === ".") {
			    if (!this.inputValue.length || this.inputValue.includes("."))
			      return false;
			  }
			  this.inputValue.push(data);
			},
			updateShopCar(){
				//关闭子组件
				this.$refs.goodsCategoryForm.close();
				//
				this.loadShopCar(false);

			},
			loadShopCar(showTips){
				let that =this;
				uni.request({
					url: app.globalData.get_request_url("getCartList"),
					method: 'POST',
					data: {
						"tenantId":this.user.role.tenantId,
						"customerId" : this.customerId,
						"createBy" : this.user.username,
					},
					header:{
						'Tenant-Id':this.user.role.tenantId,
						'X-Access-Token':this.user.token,
					},
					dataType: 'json',
					success: res => {
						if (res.data.code == 0) {
							console.log("---loadShopCar---",res.data.data)
							var data = res.data.data.data;
							if(data.length > 0){
								if(showTips){
									uni.showModal({
										title: '提示：',
										content: '检测到购物车有数据，是否添加?',
										success: function(res2) {
											if (res2.confirm) {
												that.detail_list  =res.data.data.data;
												console.log("---detail_list---",res.data.data.data)
											}
										}
									});
								}else{
									that.detail_list  =res.data.data.data;
								}
							}else{
								that.detail_list =[];
							}
						}
					},
					fail: () => {

					}
				});
			},
			initCustomer(){
				uni.request({
				    url: app.globalData.get_request_url("getCustomer"),
				    method: 'GET',
				    data: {},
					header:{
						'Tenant-Id':this.user.role.tenantId,
						'X-Access-Token':this.user.token,
					},
				    dataType: 'json',
				    success: res => {
						console.log("---------",res);
						if(res.data.code == 200){
							this.customerData =res.data.result;
						}
					}
				})
			},
			customerChange(){},
			openGoodsCategory(){
				if(this.customerId === ""){
					app.globalData.showToast('请选择客户!');
					return;
				}
				this.$refs.goodsCategoryForm.open(this.customerId);
			},
			getCurrentTime() {
			      const now = new Date();
			      const year = now.getFullYear();
			      const month = now.getMonth() + 1;
			      const day = now.getDate();
			      const hour = now.getHours();
			      const minute = now.getMinutes();
			      const second = now.getSeconds();

			      this.billDate = `${year}-${month}-${day} ${hour}:${minute}:${second}`;
			},
			goods_buy_number_event(e){
				console.log("e",e);
                var index = e.currentTarget.dataset.index || 0;
                var type = parseInt(e.currentTarget.dataset.type) || 0;
				// console.log("type",type);
				// console.log("2222",this.detail_list);
                var temp_number = parseFloat(this.detail_list[index]['stock']);
				// console.log("temp_number",temp_number);
                var buy_number = (type == 0) ? temp_number - 1 : temp_number + 1;
				// console.log("buy_number",buy_number);
				this.goods_buy_number_func(index, buy_number);
			},
			// 数量处理方法
			goods_buy_number_func(index, buy_number) {
			    var temp_data_list = this.detail_list;
			    var buy_min_number = parseInt(temp_data_list[index]['spec_buy_min_number']) || 1;
			    var buy_max_number = parseInt(temp_data_list[index]['spec_buy_max_number']) || 0;
			    var inventory = parseInt(temp_data_list[index]['inventory']);
			    var inventory_unit = temp_data_list[index]['inventory_unit'];

			    // 更新数据库
			    uni.showLoading({
			        title: '处理中...',
			        mask: true
			    });
			    uni.request({
			        url: app.globalData.get_request_url("cartUpdate"),
			        method: 'POST',
			        data: {
			            "id": temp_data_list[index]['id'],
			            "goodsId": temp_data_list[index]['goods_id'],
			            "fqty": buy_number
			        },
					header:{
						'Tenant-Id':this.user.role.tenantId,
						'X-Access-Token':this.user.token,
					},
			        dataType: 'json',
			        success: res => {
			            uni.hideLoading();
						console.log("res",res);
			            if (res.data.code == 200) {
			                var not_use = uni.getStorageSync(app.globalData.data.cache_user_cart_not_use_data_key) || {};
			                var data = res.data.data;
			                temp_data_list[index]['stock'] = data.stock;
			                temp_data_list[index]['selected'] = true;
			                delete not_use[temp_data_list[index]['id']];
			                this.setData({
			                    data_list: temp_data_list
			                });

			                // 缓存记录用户未选中的购物车数据
			                uni.setStorageSync(app.globalData.data.cache_user_cart_not_use_data_key, not_use);

							this.loadShopCar(false);

			                // 选择处理
			                // this.cart_selected_calculate();
			            } else {
			                if (app.globalData.is_login_check(res.data)) {
			                    app.globalData.showToast(res.data.msg);
			                } else {
			                    app.globalData.showToast('提交失败，请重试！');
			                }
			            }
			        },
			        fail: () => {
			            uni.hideLoading();
			            app.globalData.showToast('服务器请求出错');
			        }
			    });
			},
			openKeyBoard(e){
				var goodid =e.currentTarget.dataset.index || 0;
				console.log("goodid=",goodid);
				this.ywid =goodid;
				//this.showDigitKeyboard =false;
				//
				//清空已输入的数字
				this.inputValue = [];
				this.keyboard_status =true;
			},
			keyboard_event(e) {
			    this.setData({
			        keyboard_status: !this.keyboard_status
			    });
			},

		}
	}
</script>

<style lang="scss" scoped>
	.example {
		padding: 15px;
		background-color: #fff;
	}
	/*
	* 展示型
	*/
	.cart-exhibition-mode button {
	    line-height: 80rpx;
	}
	.cart-exhibition-mode-data .items {
	    padding-left: 0;
	}
	.cart-exhibition-mode-data .error-msg {
	    left: 26rpx;
	}
	.input-content {
	        padding-left: 50upx;
			padding-top: 10upx;
	        color: #147ff2;
	        line-height: 80upx;
	        height: 30px;
			font-size: 30upx;

	      }
	      .confirm-btn {
	        padding-right: 50upx;
			padding-top: 10upx;
	        color: #147ff2;
	        line-height: 80upx;
			font-size: 30upx;
	        position: absolute;
	        top: 0;
	        right: 0;
	      }
	.key-box {
	      margin-top: 60upx;
	      display: flex;
	      flex-flow: wrap;
	      width: 100%;
	}
	.key-box view {
	        width: 221upx;
	        height: 100upx;
	        border: 1upx solid rgb(235, 237, 240);
	        box-sizing: border-box;
	        text-align: center;
	        line-height: 100upx;
	        font-size: 40upx;
	        font-weight: bold;
	        margin: 0 -1upx -1upx 0;
	      }
		  /**
		   * 购物车
		   */
		  .cart-mask {
		      left: 0;
		      top: 0;
		      background: rgb(0, 0,0);
			  opacity: 0.6;
		      z-index: 5;
		  }
		  .cart-content {
		      left: auto;
		      bottom: 130rpx;
		      width: calc(100% - 40rpx);
		      z-index: 6;
		      max-width: calc(800px - 40rpx);
		      margin-left: 20rpx;
		  }
		  .cart-content .cart-list {
		      max-height: 60vh;
		  }
		  .cart-content .cart-list .goods-img {
		      width: 120rpx;
		      height: 120rpx !important;
		  }
		  .cart-content .cart-list .goods-base {
		      width: calc(100% - 140rpx);
		  }
		  .cart-content .cart-list .goods-base-content {
		      min-height: 60rpx;
		  }
</style>

